
import { getBaseSite } from '@/api/common';
import { useTitle, useFavicon, } from '@vueuse/core';


export async function initSiteInfo() {
  const now = Number(new Date());
  console.log('initSiteInfo')
  // 尝试从localStorage中获取所需的各项数据
  const managerSiteName = localStorage.getItem("manager_site_name");
  const managerLogo = localStorage.getItem("manager_logo");
  const managerIcon = localStorage.getItem("manager_icon");
  const manager_expiration_time = localStorage.getItem("manager_expiration_time");
  // 检查数据是否存在且未过期
  if (!managerSiteName || !managerLogo || !managerIcon || !manager_expiration_time || now > Number(manager_expiration_time)) {
    await fetchSite();
  } else {
    const title = useTitle()
    const icon = useFavicon()
    title.value = managerSiteName + " - 运营后台";
    icon.value = managerIcon;
    return {
      managerSiteName,
      managerLogo,
      managerIcon,
    }
  }
}


/**
 * 获取站点信息
 */
export async function fetchSite() {
  return getBaseSite().then((res) => {
    if (res.data.success && res.data.result.settingValue) {
      try {
        let data = JSON.parse(res.data.result.settingValue);

        // 计算过期时间并存储
        var expirationTime = JSON.stringify(new Date().setHours(new Date().getHours() + 1));
        localStorage.setItem("manager_expiration_time", expirationTime);

        // 存储站点信息
        localStorage.setItem("manager_site_name", data.siteName);
        localStorage.setItem("manager_logo", data.domainLogo);
        localStorage.setItem("manager_icon", data.domainIcon);
        localStorage.setItem('site_icp', data.icp)

        const title = useTitle()
        const icon = useFavicon()
        title.value = data.siteName + " - 运营后台";
        icon.value = data.domainIcon;
        console.log('fetchSite',data)

      } catch (error) {
        console.error("Failed", error);
      }
    }
  });
}
